package com.redis.bloom.filter.config;

import com.redis.bloom.filter.enums.RedisModeEnum;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * Redisson初始化配置类
 *
 * @author chen
 * @date 2024年02月05日 8:41
 */
@Configuration
@Slf4j
public class RedissonInitConfiguration {
    private static Map<String, RedissonClient> REDISSON_CLIENT_MAP = new HashMap<>();

    private final RedisProperties redisProperties;
    public RedissonInitConfiguration(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @PostConstruct
    public void init(){
        String address = "redis://" + this.redisProperties.getHost() + ":" + this.redisProperties.getPort();
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(address);
        singleServerConfig.setDatabase(this.redisProperties.getDatabase());
        singleServerConfig.setPassword(this.redisProperties.getPassword());
        log.info("redis单节点模式,database:{},nodes:{}", this.redisProperties.getDatabase(), address);
        RedissonClient client = Redisson.create(config);
        REDISSON_CLIENT_MAP.put(RedisModeEnum.SINGLE.toString(), client);
        log.info("成功创建Redisson客户端#集群模式={}", RedisModeEnum.SINGLE);
    }

    public static RedissonClient getDefaultClient() {
        if (REDISSON_CLIENT_MAP.isEmpty()) {
            throw new RuntimeException("获取RedissonClient对象失败,请先初始化RedissonClient对象");
        } else {
            return REDISSON_CLIENT_MAP.get(RedisModeEnum.SINGLE.toString());
        }
    }
}
